<?php
/**
 * @author qingyu8@staff.weibo.com
 * @date 2018/07/07
 */
namespace common\logic;

use Codeception\Lib\Connector\Yii1;
use common\tool\Alarm;
use EasyWeChat\Factory;
use yii;

class WechatPay {
    static $app = null;

    public static function getApp() {
        if (!self::$app) {
            $config = [
                'app_id' => Yii::$app->params['wechat']['app_id'],
                'secret' => Yii::$app->params['wechat']['secret'],
                'mch_id' => Yii::$app->params['wechat']['pay.mch_id'],
                'key' => Yii::$app->params['wechat']['pay.key'],
                'cert_path' => Yii::$app->params['wechat']['pay.cert_path'],
                'key_path' => Yii::$app->params['wechat']['pay.key_path'],
                'log' => [
                    'level' => 'debug',
                    'file' => Yii::$app->params['env']['DATA_PATH'] . 'wechat.log',
                ],
            ];

            self::$app = Factory::payment($config);
        }
        return self::$app;
    }

    public static function unifiedOrder(&$order){
        $openId = Yii::$app->session->get('wechat_openid');
        $result = self::getApp()->order->unify([
            'body' => '腾讯充值中心-QQ会员充值',
            'out_trade_no' => $order['order_id'],
            'total_fee' => $order['price'],
            //'spbill_create_ip' => '123.12.12.123', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => Yii::$app->params['host'] . '/api/v1/wechatpay/async-notify',
            'trade_type' => 'JSAPI',
            'openid' => $openId,
        ]);
        var_dump($result);
    }

    /**
     * 支付状态查询
     * @param $order
     */
    public static function query(&$order) {
        $result=self::getApp()->order->queryByOutTradeNumber($order['order_id']);

        Yii::info($result, 'debug' . __METHOD__);
    }

    public static function refund(&$order) {
        // 参数分别为：商户订单号、商户退款单号、订单金额、退款金额、其他参数
        $total_amount = Yii::$app->params['payDebug'] && in_array(Yii::$app->user->id, Yii::$app->params['debug_uids']) ? 1 : $order['price'];
        //todo 退款单号
        $num=1;
        $result = self::getApp()->refund->byOutTradeNumber($order['order_id'], $order['order_id'] . '_'.$num, $total_amount, $total_amount, [
            // 可在此处传入其他参数，详细参数见微信支付文档
            'refund_desc' => '退费',
            'notify_url' => Yii::$app->params['host'] . '/api/v1/wechatpay/refund-notify',
            //退款结果通知url
        ]);
        Yii::info($result, 'debug' . __METHOD__);
        if ($result['return_code'] == 'SUCCESS') {
            return [
                'err' => 0,
                'data' => [
                    'refund_id'=>$result['refund_id'],
                    'code' => $result['return_code'],
                    'transaction_id' => $result['transaction_id'],
                ]
            ];
        }else{
            return ['err'=>1,'msg'=>$result['return_msg']];
        }
    }

    public static function refundQuery(&$order) {
        $result = self::getApp()->refund->queryByOutTradeNumber($order['order_id']);

        Yii::info($result, 'debug' . __METHOD__);
    }
    public static function payNotify(){
        $response = self::getApp()->handlePaidNotify(function($message, $fail) {
            Yii::info($message, __METHOD__);
            if ($order = Order::getFormattedOrder($message['out_trade_no'])) {
                if (Yii::$app->params['payDebug'] && in_array($order['uid'], Yii::$app->params['debug_uids'])) {
                    $order['price'] = 1;
                }
                if ($order['order_status'] == OrderStatus::PAID) {
                    return true;
                }
                if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                    if ($message['result_code'] === 'SUCCESS') {
                        $coupon_fee = $message['coupon_fee']??0;
                        if ($message['cash_fee'] + $coupon_fee != $order['price']) {
                            Yii::error("cash_fee: {$message['cash_fee']},coupon_fee:{$coupon_fee},price:{$order['price']}", __METHOD__);
                            return $fail('支付金额有误');
                        }
                        $res = Order::pay($order['order_id'], $message['time_end'], Order::PAY_TYPE_WECHAT);
                        if ($res['err'] != 0) {
                            Yii::warning($res, __METHOD__);
                            return $fail($res['msg']);
                        }
                        Alarm::business("订单id：" . $order['order_id'], Order::PAY_TYPE_WECHAT . '订单支付成功');
                    } elseif ($message['result_code'] === 'FAIL') {
                    }
                } else {
                    return $fail('通信失败，请稍后再通知我');
                }

                return true; // 返回处理完成
            } else {
                Yii::warning($message, __METHOD__);
                return true;
            }
        });
        $response->send(); // return $response;
    }
    public static function refundNotify(){
        $response = self::getApp()->handleRefundedNotify(function ($message, $reqInfo, $fail) {
            // 其中 $message['req_info'] 获取到的是加密信息
            // $reqInfo 为 message['req_info'] 解密后的信息
            // 你的业务逻辑...
            return true; // 返回 true 告诉微信“我已处理完成”
            // 或返回错误原因 $fail('参数格式校验错误');
        });

        $response->send();

    }
}
